// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Xml.Serialization;

namespace BlueOnionSoftware.Bloget
{
    [XmlRoot("attachment")]
    public class Attachment
    {
        private string _url = string.Empty;
        private string _mimeType = string.Empty;
        private string _attachmentType = string.Empty;
        private long _length;

        public Attachment()
        {
        }

        internal Attachment(Attachment attachment)
        {
            if (attachment == null)
            {
                throw new ArgumentNullException("attachment");
            }
            _url = attachment._url;
            _mimeType = attachment._mimeType;
            _attachmentType = attachment._attachmentType;
            _length = attachment._length;
        }

        internal string Name
        {
            get
            {
                var last = _url.LastIndexOf('/');
                return (last == -1) ? _url : _url.Substring(last + 1);
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings"), XmlElement("url")]
        public string Url
        {
            get { return _url; }
            set { _url = value; }
        }

        [XmlElement("mime_type")]
        public string MimeType
        {
            get { return _mimeType; }
            set { _mimeType = value; }
        }

        [XmlElement("attachment_type")]
        public string AttachmentType
        {
            get { return _attachmentType; }
            set { _attachmentType = value; }
        }

        [XmlElement("length")]
        public long Length
        {
            get { return _length; }
            set { _length = value; }
        }

        public override string ToString()
        {
            const int kiloByte = 1024;
            const int megaByte = kiloByte*kiloByte;

            return string.Format(CultureInfo.CurrentCulture, "{0} ({1:#.##}) {2}", Name,
                                 (_length > megaByte) ? (((double) _length)/megaByte) : (((double) _length)/kiloByte),
                                 (_length > megaByte) ? "MB" : "KB");
        }
    }

    public class AttachmentCollection : Collection<Attachment>
    {
        public AttachmentCollection()
        {
        }

        internal AttachmentCollection(IEnumerable<Attachment> attachmentCollection)
        {
            if (attachmentCollection == null)
            {
                return;
            }
            foreach (var attachment in attachmentCollection)
            {
                Add(new Attachment(attachment));
            }
        }
    }
}